package com.system.insurance.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.system.common.result.Result;
import com.system.insurance.entity.AppletUser;
import com.system.insurance.entity.Frequency;
import com.system.insurance.entity.OfferRecord;
import com.system.insurance.entity.Reward;
import com.system.insurance.mapper.OfferRecordMapper;
import com.system.insurance.service.AppletUserService;
import com.system.insurance.service.FrequencyService;
import com.system.insurance.service.OfferRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.system.insurance.service.RewardService;
import com.system.insurance.utils.AuthContextUtil;
import com.system.insurance.utils.HttpUtils;
import com.system.insurance.utils.WePayConfig;
import com.system.insurance.utils.WechatPay2ValidatorForRequest;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WS
 * @since 2024-05-21
 */
@Service
public class OfferRecordServiceImpl extends ServiceImpl<OfferRecordMapper, OfferRecord> implements OfferRecordService {

    protected static final Logger log = LoggerFactory.getLogger(WechatPay2Validator.class);


    @Autowired
    private AppletUserService appletUserService;
    @Autowired
    private WePayConfig wxPayConfig;

//    @Resource
//    private CloseableHttpClient wxPayClient;
    @Autowired
    private OfferRecordService offerRecordService;



//    @Resource
//    private Verifier verifier;


    @Autowired
    private RewardService rewardService;


    @Autowired
    private FrequencyService frequencyService;


//        @SneakyThrows
//        @Override
//        @Transactional
//        public Object CarteOrdersPay(HttpServletRequest request, HttpServletResponse response, OfferRecord orderDetail) {
//
//            String s = AuthContextUtil.get();
//            AppletUser byId = appletUserService.getById(Integer.valueOf(s));
//            try {
//                request.setCharacterEncoding("UTF-8");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            response.setCharacterEncoding("UTF-8");
//
//            OfferRecord byIdDetail = offerRecordService.getById(orderDetail.getId());
//            log.info("ing: " + byIdDetail);
//
////        Topic byId1 = topicService.getById(topicId);
//
//            if (byIdDetail != null && byIdDetail.getAppletUserId() != null && byIdDetail.getOrderNumber() != null && byIdDetail.getPrice() != null) {
//                log.info("生成订单");
//                HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
//
//                Gson gson = new Gson();
//                JSONObject paramsMap = new JSONObject();
//                paramsMap.put("appid", wxPayConfig.getAppId());// appid
//                paramsMap.put("mchid", wxPayConfig.getMchId());// 商户号
////            paramsMap.put("description", byIdDetail.getRewardReason());// 商品描述
//                paramsMap.put("description", "询价端解锁付费方案");
//                paramsMap.put("attach",AuthContextUtil.get());
//                paramsMap.put("out_trade_no", byIdDetail.getOrderNumber());// 商户订单号
//                //TODO    域名需要更改
//                paramsMap.put("notify_url", "https://");
//
//                JSONObject amountMap = new JSONObject();
//
//                BigDecimal intPrice = byIdDetail.getPrice().multiply(new BigDecimal("100"));
//
//                // 如果需要将结果转换为整数，可以使用round方法四舍五入到最接近的整数
//                int price = intPrice.setScale(0, RoundingMode.HALF_UP).intValue();
//
//                log.info("price金额: " + price);
//                amountMap.put("total", price); // 金额
//                amountMap.put("currency", "CNY"); // 货币类型
//                paramsMap.put("amount", amountMap);
//                log.info("金额：" + amountMap);
//                JSONObject playerMap = new JSONObject();
//
//                playerMap.put("openid", byId.getOpenid());// 用户openid
//                paramsMap.put("payer", playerMap);
//
//                // 将参数转化为json字符串
//                String jsonParamsMap = gson.toJson(paramsMap);
//                log.info("请求参数：" + jsonParamsMap);
//
//                StringEntity entity = new StringEntity(jsonParamsMap, "utf-8");
//                entity.setContentType("application/json");
//                httpPost.setEntity(entity);
//                httpPost.setHeader("Accept", "application/json");
//
//                // 完成签名并执行请求
//                try (CloseableHttpResponse resp = wxPayClient.execute(httpPost)) {
//                    int statusCode = resp.getStatusLine().getStatusCode();
//                    String bodyAsString = EntityUtils.toString(resp.getEntity());
//                    // 响应结果
//                    HashMap<String, String> resultMap = gson.fromJson(bodyAsString, HashMap.class);
//                    // 获取prepay-id
//                    String prepayId = resultMap.get("prepay_id");
//                    // 获取到prepayId之后需要对数据进行二次封装，前端调起支付必须存在的参数
//                    HashMap<String, String> payMap = new HashMap<>();
//                    payMap.put("appid", wxPayConfig.getAppId());// appid
//                    long currentTimestamp = System.currentTimeMillis();// 时间戳
//                    payMap.put("timeStamp", currentTimestamp + "");
//                    String nonceStr = UUID.randomUUID().toString()
//                            .replaceAll("-", "")
//                            .substring(0, 32);
//                    // 随机字符串
//                    payMap.put("nonceStr", nonceStr);
//                    // apiv3只支持这种加密方式
//                    payMap.put("signType", "RSA");
//                    payMap.put("package", "prepay_id=" + prepayId);
//
//                    String aPackage = wxPayConfig.buildMessageTwo(wxPayConfig.getAppId(), currentTimestamp, nonceStr, payMap.get("package"));
//                    // 获取对应的签名
//                    String paySign = wxPayConfig.sign(aPackage.getBytes("utf-8"));
//                    payMap.put("paySign", paySign);
//
//                    payMap.put("orderNumber", byIdDetail.getOrderNumber());
//
//                    if (statusCode == 200) {
//                        log.info("成功，返回结果 = " + bodyAsString);
//                        log.info("前端用：" + payMap);
//                        return payMap;
//
//                    } else if (statusCode == 204) {
//                        log.info("成功，返回结果 = ");
//
//                        log.info("前端用：" + payMap);
//                        return payMap;
//
//                    } else {
//                        log.info("小程序下单失败,响应码 = " + statusCode + ",返回结果 = " + bodyAsString);
//                        log.info("前端用：" + payMap);
//                        return payMap;
//                    }
//                }
//            }
//            return null;
//        }
//
//    /**
//     * 微信付款通知回调地址
//     * @param request
//     * @param response
//     * @return
//     */
//    @Override
//    public Object wxBuy(HttpServletRequest request, HttpServletResponse response) {
//        Gson gson = new Gson();
//        //创建一个应答对象
//        Map<String, String> map = new HashMap<>();
//        try {
//            //处理通知参数
//            String body = HttpUtils.readData(request);
//            HashMap<String, Object> bodyMap = gson.fromJson(body, HashMap.class);
//            String requestId = (String) bodyMap.get("id");
//            log.info("支付通知的id=====》》》{}", bodyMap.get("id"));
//            //签名的验证
//            WechatPay2ValidatorForRequest wechatPay2ValidatorForRequest = new WechatPay2ValidatorForRequest(verifier, requestId, body);
//            if (!wechatPay2ValidatorForRequest.validate(request)) {
//                log.error("通知验签失败");
//                //通知失败应答
//                response.setStatus(500);
//                map.put("code", "ERROR");
//                map.put("message", "通知验签失败");
//                return map;
//            }
//            log.info("通知验签成功");
//
//            //解密密文，获取明文
//            String plaintText = wxPayConfig.decryptFromResource(bodyMap);
//            //将明文转为map
//            HashMap plaintTextMap = gson.fromJson(plaintText, HashMap.class);
//            //获取支付下单的时候，传入的商户订单号,可以根据这个订单号去获取我们的一个订单记录，从而更新订单状态
//            String orderNo = (String) plaintTextMap.get("out_trade_no");
//            //业务编号
//            String transactionId = (String) plaintTextMap.get("transaction_id");
//            //trade_type，支付类型,如果有需要的话， 你可以存储在数据库中，这里我们的数据，基本上都是JSapi支付类型
//            //交易状态
//            String tradeState = (String) plaintTextMap.get("trade_state");
//            //附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
//            String attach = (String) plaintTextMap.get("attach");
//
//            String successTime = (String) plaintTextMap.get("success_time");
//
//            Map<String,Object> amount = (Map<String, Object>) plaintTextMap.get("amount");
//            String payer_total =String.valueOf(amount.get("payer_total"));
//
//            Reward reward = new Reward();
//            reward.setTransactionid(transactionId);
//            reward.setOuttradeno(orderNo);
//            reward.setPrice(payer_total);
//            reward.setSuccesstime(successTime);
//            reward.setStart(tradeState);
//            reward.setCreateTime(LocalDateTime.now());
//            reward.setAppletUserId(Integer.valueOf(attach));
//            boolean save = rewardService.save(reward);
//
//            AppletUser byId = appletUserService.getById(Integer.valueOf(attach));
//            //consume.add(orderPrepayId.getPrice())
//            BigDecimal consume = byId.getPrice();
//            BigDecimal bigDecimal12 =new  BigDecimal(payer_total);
//
//            BigDecimal bigDecimal13 =new  BigDecimal("100");
//            byId.setPrice(consume.add(bigDecimal12.divide(bigDecimal13)));
//            byId.setNum(byId.getNum()+1);
//            appletUserService.updateById(byId);
//
//
//            LambdaQueryWrapper<Frequency> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(Frequency::getAppletuserid,byId.getId());
//            Frequency one = frequencyService.getOne(wrapper);
//
//            one.setEnquiry(one.getEnquiry()+1);
//            frequencyService.updateById(one);
//
//
//            LambdaQueryWrapper<OfferRecord> wrapper1 = new LambdaQueryWrapper<>();
//            wrapper1.eq(OfferRecord::getOrderNumber,orderNo);
//            OfferRecord one1 = offerRecordService.getOne(wrapper1);
//
//            if (tradeState.equals("SUCCESS")) {
//                one1.setStart(1);
//            }else {
//                one1.setStart(0);
//            }
//            offerRecordService.updateById(one1);
//
//            //成功应答
//            response.setStatus(200);
//            map.put("code", "SUCCESS");
//            map.put("message", "成功");
//            return gson.toJson(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//            //失败应答
//            response.setStatus(500);
//            map.put("code", "ERROR");
//            map.put("message", "失败");
//            return gson.toJson(map);
//        }
//    }
//
//    @Override
//    public OfferRecord getOrders(String orderId) {
//        LambdaQueryWrapper<OfferRecord> lambdaQueryWrapper = new LambdaQueryWrapper();
//        lambdaQueryWrapper.eq(OfferRecord::getOrderNumber,orderId);
//        OfferRecord orderDetail = offerRecordService.getOne(lambdaQueryWrapper);
//        if (orderDetail != null) {
//            return orderDetail;
//        }
//        return null;
//    }

//    @Override
//    public Object queryOderStatus(String orderNumber) {
//
//        String url = "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + orderNumber + "?mchid=" + wxPayConfig.getMchId();
//        HttpGet httpGet = new HttpGet(url);
//        httpGet.setHeader("Accept", "application/json");
//        //完成签名并执行请求
//        CloseableHttpResponse resp = null;
//        try {
//            resp = wxPayClient.execute(httpGet);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        try {
//            int statusCode = resp.getStatusLine().getStatusCode();
//            String bodyAsString = null;
//            try {
//                bodyAsString = EntityUtils.toString(resp.getEntity());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if (statusCode == 200) { //处理成功
//                log.info("成功，返回结果 = " + bodyAsString);
//            } else if (statusCode == 204) { //处理成功，无返回Body
//                log.info("成功");
//            } else {
//                System.out.println("小程序下单失败,响应码 = " + statusCode + ",返回结果 = " + bodyAsString);
//                try {
//                    throw new IOException("request failed");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            log.info("bodyAsString:" + bodyAsString);
//            return Result.ok(bodyAsString);
//        } finally {
//            try {
//                resp.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

}
